package com.example.demo.Controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.QueryPageParam;
import com.example.demo.common.Result;
import com.example.demo.entity.Adoption;
import com.example.demo.entity.Notification;
import com.example.demo.entity.User;
import com.example.demo.service.IAdoptionService;
import com.example.demo.service.INotificationService;
import com.example.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author demo
 * @since 2025-02-28
 */
@RestController
@RequestMapping("/adoption")
public class AdoptionController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IAdoptionService adoptionService;

    @Autowired
    private INotificationService notificationService;
    //新增
    @PostMapping("/save")
    public Result save(
            @RequestParam("petNo") Integer petNo,
            @RequestParam(value = "imageFile", required = false) MultipartFile imageFile){

        Adoption adoption = new Adoption();
        adoption.setPetNo(petNo);

        try {
            if (imageFile != null && !imageFile.isEmpty()) {
                // 校验文件大小
                if (imageFile.getSize() > 2 * 1024 * 1024) {
                    return Result.fail();
                }
                //图片类型校验
                String contentType = imageFile.getContentType();
                if (!Arrays.asList("image/jpeg", "image/png").contains(contentType)) {
                    return Result.fail("仅支持JPEG/PNG格式");
                }
                adoption.setPetImage(imageFile.getBytes());
                adoption.setImageType(contentType);
            }
            boolean saveResult = adoptionService.save(adoption);
            return saveResult ? Result.suc() : Result.fail("数据库保存失败");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("文件处理失败: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("系统异常: " + e.getMessage());
        }

    }

    /*用户领养申请接口*/
    @PostMapping("/submit")
    public Result submitAdoption(
            @RequestParam("petNo") Integer petNo,
            @RequestParam("petName") String petName,
            @RequestParam("adopterNo") String adopterNo,
            @RequestParam("content") String content
    ) {
        System.out.println("petNo: " + petNo + "petName: " + petName + ", adopterNo: " + adopterNo + ", content: " + content);
        Adoption adoption = new Adoption();
        adoption.setPetNo(petNo);
        adoption.setPetName(petName);
        adoption.setAdopterNo(adopterNo);
        adoption.setContent(content);
        adoption.setApplyStatus(0); // 0-待处理
        adoption.setAdoptTime(LocalDateTime.now());

        adoption.setStatus(200);

        boolean saveResult = adoptionService.save(adoption);
        if (!saveResult) {
            return Result.fail("提交申请失败");
        }

        List<User> admins = userService.lambdaQuery()
                .in(User::getRoleId, Arrays.asList(0, 1))
                .list();
        // 生成管理员通知
        for (User admin : admins) {
            Notification notification = new Notification();
            notification.setType(1); // 领养类通知
            notification.setUserId(admin.getNo()); // 动态设置管理员账号
            notification.setContent("用户 " + adopterNo + " 申请领养宠物 "+ petName + "（编号: " + petNo + " ),理由是：" + content);
            notification.setStatus(0); // 未处理
            notification.setCreateTime(LocalDateTime.now());
            notification.setRelatedId(adoption.getId()); // 关联领养记录ID
            notificationService.save(notification);
        }
        return Result.suc();
    }

    //更新
    @PostMapping("/update")
    public Result update(@RequestBody Adoption adoption){
        return adoptionService.updateById(adoption)?Result.suc():Result.fail();
    }

    //删除
    @GetMapping("/del")
    public Result del(@RequestParam Long id){
        return adoptionService.removeById(id)?Result.suc():Result.fail();
    }

    //图片获取接口
    @GetMapping("/image/{id}")
    public void getImage(@PathVariable Long id, HttpServletResponse response)throws IOException {
        Adoption adoption = adoptionService.getById(id);
        if (adoption == null || adoption.getPetImage() == null) {
            response.sendError(404, "Image not found");
            return;
        }
        String contentType = adoption.getImageType();
        response.setContentType(contentType != null ? contentType : "image/jpeg");
        response.getOutputStream().write(adoption.getPetImage());

    }

    //图片上传接口
    @PostMapping("/uploadImage")
    public Result uploadImage(@RequestParam("file") MultipartFile file,
                              @RequestParam String adoptionId)
            throws IOException{
        if (file.isEmpty()) {
            return Result.fail();
        }
        if (!Arrays.asList("image/jpeg", "image/png").contains(file.getContentType())) {
            return Result.fail();
        }
        if (file.getSize() > 2 * 1024 * 1024) {
            return Result.fail();
        }
        Adoption adoption = adoptionService.getById(adoptionId);
        if (adoption == null) {
            return Result.fail();
        }
        //直接存储二进制数据，文件类型
        adoption.setImageType(file.getContentType());
        adoption.setPetImage(file.getBytes());
        //更新用户数据
        return adoptionService.updateById(adoption) ? Result.suc() : Result.fail();
    }

    @PostMapping("/listPageA")
    public Result listPageA(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        String keywords = (String)param.get("keywords");

        Page<Adoption> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<Adoption> lambdaQueryWrapper = new LambdaQueryWrapper();
        if (StringUtils.isNotBlank(keywords) && !"null".equals(keywords)){
            lambdaQueryWrapper.and(wrapper ->
                    wrapper.like(Adoption::getPetNo, keywords)
                            .or()
                            .like(Adoption::getPetName, keywords)
                            .or()
                            .like(Adoption::getAdopterNo, keywords)
            );
        }
        System.out.println("查询条件: " + lambdaQueryWrapper.getCustomSqlSegment());
        IPage result = adoptionService.pageA(page,lambdaQueryWrapper);
        List<Adoption> records = result.getRecords();
        return  Result.suc(records,result.getTotal());

    }

    @PostMapping("/process")
    public Result processAdoption(
            @RequestParam Long id,
            @RequestParam Integer applyStatus, // 1-通过, 2-拒绝
            @RequestParam(required = false) String reason
    ) {
        // 1. 更新领养申请状态
        Adoption adoption = adoptionService.getById(id);
        if (adoption == null) {
            return Result.fail("领养记录不存在");
        }
        adoption.setApplyStatus(applyStatus);
        if (applyStatus == 1) {
            adoption.setStatus(200); // 假设200表示健康状态
        }
        adoptionService.updateById(adoption);

        // 2. 生成用户通知
        String content = applyStatus == 1 ?
                "您的领养申请已通过！" :
                "您的申请被拒绝，原因：" + reason;
        Notification userNotification = new Notification();
        userNotification.setUserId(adoption.getAdopterNo());
        userNotification.setContent(content);
        userNotification.setStatus(1); // 直接标记为已读
        userNotification.setCreateTime(LocalDateTime.now());
        userNotification.setRelatedId(id);
        notificationService.save(userNotification);

        return Result.suc();
    }

}
